<template>
    <div class="app-content">
      <el-dialog title="腾讯地图坐标选择器" width="1180px" top="20px" :visible.sync="show" :before-close="closeForm" append-to-body>
            <el-input size="small" @input="getLatLngBounds()" suffix-icon="el-icon-location" v-model="address" autoComplete="off" clearable  placeholder="请输入搜索地址" style="width: 60%;"></el-input>
            <span>经度：</span><el-input size="small" v-model="lng" placeholder="请输入经度" style="width:150px;"></el-input>&nbsp;&nbsp;&nbsp;
            <span>维度：</span><el-input size="small" v-model="lat" placeholder="请输入维度" style="width:150px;"></el-input>
            <el-button size="small" type="primary" @click="searchAddress">查询</el-button>
            <div class="content" ref="bounds">
                <div v-if="showaddress" class="showaddress" style="width: 60%;overflow:hidden">
                  <p class="close" @click="showaddress = false">关闭</p>
                  <p v-for="(i,index) in BoundsPois" :key="index" @click="selectCity(index,i)" style="width: 60%;overflow:hidden">
                      {{i.name}}
                      <span class="address">{{i.address}}</span>
                  </p>
                </div>
                <div id="map"></div>
            </div>
             <div slot="footer" class="dialog-footer">
              <el-button size="small" type="primary" @click="submit" >
                <span>确 定</span>
              </el-button>
              <el-button size="small" @click="closeForm">取 消</el-button>
            </div>
      </el-dialog>
    </div>
</template>

<script>
export default {
  props: {
    //地图key
    mapKey: {
      type: String,
      default: 'UBIBZ-4RDKX-B3X4O-ZHA6W-3DXAZ-FVBLB'
    },
    //周边位置高度
    boundsHeight: {
      type: String,
      default: '200px'
    },
    show: {
        type: Boolean,
        default: false
    },
    address_detail:{
        type:String,
        default:null
    },
  },
  data() {
    let points =  this.address_detail ? JSON.parse(this.address_detail) : {lng:'',lat:'',address:''}
    return {
      lat:points.lat,
      lng:points.lng,
      address: points.address, //搜索关键字
      marker: null, //标记点
      map: null, //地图实例
      setTime: null,
      selectPosition: -1,  //选择的位置
      BoundsPois: [], //周边列表,
      showaddress:true
    };
  },

  mounted() {
    this.loadScript()
  },

  methods: {
    //异步加载地图js
    loadScript() {
      var script = document.createElement("script")
      script.type = "text/javascript";
      window.initMap = () => {
        this.init()
      };
      script.src ="https://map.qq.com/api/js?v=2.exp&key=" +this.mapKey +"&callback=initMap"
      document.body.appendChild(script);
    },

    //初始化地图
    init() {
      this.map = new qq.maps.Map(document.getElementById("map"), {
        center: new qq.maps.LatLng(this.lat, this.lng), //设置地图中心的
        keyboardShortcuts: false,  //禁止键盘操控
        disableDefaultUI: true,    //禁止所有控件
        zoom: 16 //原16
      });
      if(!this.lat){
        this.getLocation();
      }else{
        let latLng = new qq.maps.LatLng(this.lat, this.lng)
        this.setMarker(latLng);
      }
      
      //绑定地图点击事件
      qq.maps.event.addListener(this.map, "click", e => {
          let latLng = new qq.maps.LatLng(e.latLng.lat, e.latLng.lng)
          //吧实时选中的坐标赋值给经度和维度
          this.lat = e.latLng.lat
          this.lng = e.latLng.lng
          this.marker.setPosition(latLng)
          this.marker.setAnimation(qq.maps.MarkerAnimation.DOWN)
          //this.getAddress(latLng)
      });
      //绑定地图中心点改变事件
      qq.maps.event.addListener(this.map, "center_changed", e => {
        if(this.selectPosition != -1) return;
        this.centerChanged(e);
      });
      //绑定地图开始拖动事件
      qq.maps.event.addListener(this.map, "dragstart", e => {
        //重置选择、搜索框
        this.address = '';
        this.selectPosition = -1;
      });
      //绑定地图缩放级别更改事件
      qq.maps.event.addListener(this.map, "zoom_changed", e => {
        //重置选择、搜索框
        this.address = '';
        this.selectPosition = -1;
      });
    },

    //地图中心点改变事件
    centerChanged(e, type) {
      let center = this.map.getCenter();
      if (this.marker) {
        this.marker.setPosition(center);
        this.marker.setAnimation(qq.maps.MarkerAnimation.DOWN);
      }
    },

    //查询位置
    searchCity() {
      let geocoder = new qq.maps.Geocoder({
        complete: result => {
          this.map.setCenter(result.detail.location);
          //设置标注点位置
          this.marker.setPosition(result.detail.location);
          //设置标注点下落动画
          this.marker.setAnimation(qq.maps.MarkerAnimation.DOWN);
        }
      });
      geocoder.getLocation(this.address);
    },

    //搜索位置，查询周边位置信息
    getLatLngBounds(init) {
      this.selectPosition = -1;
      let latlngBounds = new qq.maps.LatLngBounds();
      //调用Poi检索类
      let searchService = new qq.maps.SearchService({
        complete: results => {
          this.scrollTop();
          this.BoundsPois = results.detail.pois;
          this.map.setCenter(this.BoundsPois[0].latLng);
          //设置标注点为中心点
          this.marker.setPosition(this.BoundsPois[0].latLng);
        }
      });
      //周边位置个数10个
      searchService.setPageCapacity(20);
      searchService.searchInBounds(this.address, latlngBounds); //根据范围和关键字进行指定区域检索。
    },

    searchAddress() {
      this.getAddress(new qq.maps.LatLng(this.lat, this.lng));
    },

    //根据经纬度进行位置解析
    getAddress(latLng) {
      let geocoder = new qq.maps.Geocoder({
        complete: result => {
          this.scrollTop();
          if (result.detail.nearPois.length > 0) {
            this.showaddress = true
          }
          //添加当前的经纬度信息
          let nowPostin = {name: '当前标注位置', address: result.detail.address, latLng: {lat: result.detail.location.lat, lng: result.detail.location.lng}};
          this.BoundsPois = [nowPostin, ...result.detail.nearPois];
        }
      });
      geocoder.getAddress(latLng || this.map.getCenter());
    },

    //选择周边滚动条返回到顶部
    scrollTop () {
      this.$refs.bounds.scrollTop = 0;
    },

    //在列表中选择位置
    selectCity (index,row) {
      this.selectPosition = index;
      let lat = this.BoundsPois[index].latLng.lat,
          lng = this.BoundsPois[index].latLng.lng,
          latLng = new qq.maps.LatLng(lat, lng);
      //将地图中心移至当前坐标
      this.map.panTo(latLng);
      //设置标注点位置
      this.marker.setPosition(latLng);
      //设置标注点下落动画
      this.marker.setAnimation(qq.maps.MarkerAnimation.DOWN);

      this.address = row.address + row.name
      this.lat = lat
      this.lng = lng
      this.showaddress = false
      
    },

    //获取当前位置
    getLocation() {
      let cs = new qq.maps.CityService({
        map: this.map,
        complete: results => {
          this.latLng = [results.detail.latLng.lat, results.detail.latLng.lng];
          //设置地图中心位置为当前定位。
          this.map.setCenter(results.detail.latLng);
          //设置标注点为当前中心位置
          this.setMarker(results.detail.latLng);
          //获取当前位置的周边范围
          //this.getAddress();
        }
      });
      //调用searchLocalCity()方法获取位置
      cs.searchLocalCity();
    },

    //设置底部标记点
    setMarker(center) {
      let icon = new qq.maps.MarkerImage(
        "",
        new qq.maps.Size(52, 73),
        new qq.maps.Point(0, 0),
        new qq.maps.Point(12, 34),
        new qq.maps.Size(45, 65)
      );
      this.marker = new qq.maps.Marker({
        map: this.map,
        position: center
      });
      this.marker.setIcon(icon);
    },
    submit(){
        let address = {address:this.address,lng:this.lng,lat:this.lat}
        this.$emit('update:address_detail', JSON.stringify(address))
        this.$emit('returnFn', address)
        this.closeForm()
    },
    closeForm(){
        this.$emit('update:show', false)
    }
  }
};
</script>
<style lang="scss" scoped>
.content {
      width: 100%;
      //height: 600px;
      background: rgba(252, 250, 250, 0.918);
      border: 1px solid #f1f1f1;
      border-top: none;
      font-size: 13px;
      color: #5a5a5a;
      max-height: 600px;
      overflow-y: auto;
      .showaddress {
        position: relative;
        width: 60%;
        .close {
          position:absolute;
          top: 5px;
          right: 5px;
        }
      }
      p {
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
        padding: 8px 10px;
        margin: 0;
        cursor: pointer;
        &:hover {
          background: #eff6fd;
        }
        .address {
          font-size: 12px;
          color: #b9b9b9;
          margin-left: 20px;
        }
      }
}
#map {
  height: 500px;
}
</style>
